/**
 * 
 */
package com.example.ourapps.repo;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.example.ourapps.domain.AppDetail;

/**
 * @author richapahwa
 *
 */
@Repository
@Transactional
public class AppDetailDaoImpl implements AppDetailDao {

	@Autowired
	private EntityManager em;
	
	/* (non-Javadoc)
	 * @see com.example.ourapps.repo.AppDetailDao#findById(java.lang.Long)
	 */
	@Override
	public AppDetail findById(Long anId) {
		return em.find(AppDetail.class, anId);
	}

	/* (non-Javadoc)
	 * @see com.example.ourapps.repo.AppDetailDao#findByAppName(java.lang.String)
	 */
	@Override
	public AppDetail findByAppName(String anApplicationName) {
		final CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
		final CriteriaQuery<AppDetail> appDetailQuery = criteriaBuilder.createQuery(AppDetail.class);
		final Root<AppDetail> appDetail = appDetailQuery.from(AppDetail.class);
		
		appDetailQuery.select(appDetail).where(criteriaBuilder.equal(appDetail.get("applicationName"), anApplicationName));
		return em.createQuery(appDetailQuery).getSingleResult();
	}

	/* (non-Javadoc)
	 * @see com.example.ourapps.repo.AppDetailDao#findAllRegisteredApps()
	 */
	@Override
	public List<AppDetail> findAllRegisteredApps() {
		final CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
		final CriteriaQuery<AppDetail> appDetailQuery = criteriaBuilder.createQuery(AppDetail.class);
		final Root<AppDetail> appDetail = appDetailQuery.from(AppDetail.class);
	
		appDetailQuery.select(appDetail).where(criteriaBuilder.equal(appDetail.get("registered"), Boolean.TRUE));
		return em.createQuery(appDetailQuery).getResultList();
	}
	

	/* (non-Javadoc)
	 * @see com.example.ourapps.repo.AppDetailDao#register(com.example.ourapps.domain.AppDetail)
	 */
	@Override
	public void register(AppDetail anAppDetail) {
		em.persist(anAppDetail);
	}

}
